package com.suieqian.filter.logFile;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lirch
 */
//@ControllerAdvice
//@Order(2)
@Slf4j
public class LogResponseBodyHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (serverHttpRequest instanceof ServletServerHttpRequest &&
                serverHttpResponse instanceof ServletServerHttpResponse) {
            HttpServletRequest request = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
            if (request.getAttribute("myInterceptor_startTime") != null) {
                long startTime = (Long) request.getAttribute("myInterceptor_startTime");
                String requestId = request.getAttribute("myInterceptor_requestId").toString();

                long endTime = System.currentTimeMillis();
                long executeTime = endTime - startTime;
                String resultStr = JSONUtil.toJsonStr(o);
                if (StrUtil.isBlank(resultStr) || resultStr.length() > 1000) {
                    resultStr = "";
                }
                log.info("请求结束requestId:" + requestId + "==用时:" + executeTime + "ms===返回值:" + resultStr);
            }
        }
        return o;
    }
}
